package com.gfinal.wechatmap;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.gfinal.map.bus.LineBean;
import com.gfinal.map.bus.LineSearch;
import com.gfinal.map.bus.StatBean;
import com.gfinal.map.bus.StatsSearch;
import com.gfinal.map.direction.DirectionBean;
import com.gfinal.map.direction.Route;
import com.gfinal.map.direction.RouteSearch;
import com.gfinal.map.direction.Scheme;
import com.gfinal.map.direction.Step;
import com.gfinal.map.direction.Taxi;
import com.gfinal.map.direction.TransitStep;
import com.gfinal.map.geo.GeoBean;
import com.gfinal.map.geo.ReGeoCoding;
import com.gfinal.map.place.DetailInfo;
import com.gfinal.map.place.POIBean;
import com.gfinal.map.place.POISearch;
import com.gfinal.map.util.HttpUtils;

/**
 * 地图微信端处理
 * 
 * @author GuoWenfeng && GaoYudong
 * @date 2015年3月10日
 */
public class MapServiceHandler {
	/**
	 * 调试，上线置false
	 */
	private boolean DEBUG = false;

	private static final String TAG = MapServiceHandler.class.getName();

	private static final String MAP_PAGE_URL = "http://tourservice.rsvptech.cn/tourweb/bymap?json=";
	private static final String DEFAULT_MAP_PIC_URL = "http://resource.rsvptech.cn/download/map.jpg";

	/* topic */
	private static final String TOPIC_CAR_ROUTE_QUERY = "Car_Route_Query";
	private static final String TOPIC_CAR_ROUTE_NEARBY_QUERY = "Car_Route_Nearby_Query";
	private static final String TOPIC_CAR_ROUTE_TEXI_QUERY = "Car_Route_Texi_Query";
	private static final String TOPIC_CAR_ROUTE_QUERY_WITHMID_POINT = "Car_Route_Query_With_Mid_Point";
	private static final String TOPIC_CAR_ROUTE_WITH_MID_ROAD = "Car_Route_Query_With_Mid_Road";
	private static final String TOPIC_DISTANCE_QUERY = "Distance_Query";
	private static final String TOPIC_CURRENT_LOCATION_QUERY = "CurrentLocation_Query";
	private static final String TOPIC_POI_QUERY = "Poi_Query";
	private static final String TOPIC_POI_POSTCODE_QUERY = "Poi_PostCode_Query";
	private static final String TOPIC_POI_PHONE_QUERY = "Poi_Phone_Query";
	private static final String TOPIC_BUS_ROUTE_QUERY = "Bus_Route_Query";
	private static final String TOPIC_BUS_LINE_QUERY = "Bus_Line_Query";
	private static final String TOPIC_BUS_STATION_QUERY = "Bus_Station_Query";

	/* direction tactics */
	private static final String TACTICS_DRIVING_FAST = "DRIVING_TYPE_FASTEST";
	private static final String TACTICS_DRIVING_SHORTEST = "DRIVING_TYPE_SHORTEST";
	private static final String TACTICS_DRIVING_NOHIGHWAY = "DRIVING_TYPE_NOHIGHWAY";
	private static final String TACTICS_BUS_FASTEST = "BUS_TYPE_FASTEST";
	private static final String TACTICS_BUS_NOTSUBWAY = "BUS_TYPE_NOTSUBWAY";
	private static final String TACTICS_BUS_LESSCHANGE = "BUS_TYPE_LESSCHANGE";
	private static final String TACTICS_BUS_LESSWALK = "BUS_TYPE_LESSWALK";

	/* bus line type */
	private static final String BUS_LINE_FIRST_TIME = "bus_first_time";
	private static final String BUS_LINE_LAST_TIME = "bus_last_time";
	private static final String BUS_LINE_FIRST_LAST_TIME = "bus_first_last_time";
	private static final String BUS_LINE_CHECK_LINE_STATION = "check_line_station";
	private static final String BUS_LINE_CHECK_LINE_TIME = "check_line_time";
	private static final String BUS_LINE_LIST_LINE_STATION = "list_line_station";

	/* route mode */
	private static final String DIRECTION_MODE_DRIVING = "driving";
	private static final String DIRECTION_MODE_WALKING = "walking";
	private static final String DIRECTION_MODE_TRANSIT = "transit";

	private static final String CURRENT_LOCATION = "CurrentLocation";

	private static final int DEFAULT_RADIUS = 3000;

	private static MapServiceHandler mInstence = null;

	private String mMapPageUrl = null;
	private String mQuestion = null;

	private MapServiceHandler() {
	}

	public static MapServiceHandler getInstence() {
		if (mInstence == null) {
			mInstence = new MapServiceHandler();
		}
		return mInstence;
	}

	public JSONArray execute(String msg, double lat, double lon, String content)
			throws JSONException {
		JSONArray array = null;

		if (msg == null || msg.equals("")) {
			return null;
		}

		JSONObject msgObj = new JSONObject(msg);
		String domain = msgObj.getString("domain");
		if (!domain.equalsIgnoreCase("Map")) {
			return null;
		}
		int status = msgObj.getInt("status");
		if (status != 0) {
			return null;
		}

		JSONArray answerArr = msgObj.getJSONArray("answer");
		if (answerArr == null || answerArr.length() == 0) {
			return null;
		}

		JSONObject answerObj = answerArr.getJSONObject(0);
		String topic = answerObj.getString("topic");
		if (topic == null) {
			return null;
		}

		String currentCity = null;
		ReGeoCoding search = new ReGeoCoding();
		search.setLat((float) lat);
		search.setLng((float) lon);
		search.setPois(0);
		GeoBean geo = search.execute();
		if (geo != null && geo.getAddressComponent() != null) {
			currentCity = geo.getAddressComponent().getCity();
		}
		if (currentCity == null || "".equals(currentCity)) {
			currentCity = "全国";
		}
		if (DEBUG) {
			currentCity = "宁波";
			lat = 29.875964;
			lon = 121.560824;
		}

		mMapPageUrl = MAP_PAGE_URL + msg + "&lat=" + lat + "&lng=" + lon;
		mQuestion = content;
		String latlon = lat + "," + lon;

		/* prepare parameter */
		String start = null;
		if (answerObj.has("start")) {
			start = answerObj.getString("start");
		}
		if (start != null && start.equalsIgnoreCase(CURRENT_LOCATION)) {
			if (geo != null && !geo.getFormatted_address().equalsIgnoreCase("")) {
				start = geo.getFormatted_address();
			} else {
				start = latlon;
			}
		}

		String end = null;
		if (answerObj.has("end")) {
			end = answerObj.getString("end");
		}
		if (end != null && end.equalsIgnoreCase(CURRENT_LOCATION)) {
			if (geo != null && !geo.getFormatted_address().equalsIgnoreCase("")) {
				end = geo.getFormatted_address();
			} else {
				end = latlon;
			}
		}

		String mid = null;
		if (answerObj.has("mid")) {
			mid = answerObj.getString("mid");
		}
		if (mid != null && mid.equalsIgnoreCase(CURRENT_LOCATION)) {
			if (geo != null && !geo.getFormatted_address().equalsIgnoreCase("")) {
				mid = geo.getFormatted_address();
			} else {
				mid = latlon;
			}
		}

		String type = null;
		if (answerObj.has("type")) {
			type = answerObj.getString("type");
		}
		int tictics = 10;
		if (type != null) {
			if (type.equalsIgnoreCase(TACTICS_DRIVING_FAST)) {
				tictics = 11;
			} else if (type.equalsIgnoreCase(TACTICS_DRIVING_SHORTEST)) {
				tictics = 12;
			} else if (type.equalsIgnoreCase(TACTICS_DRIVING_NOHIGHWAY)) {
				tictics = 10;
			} else if (type.equalsIgnoreCase(TACTICS_BUS_FASTEST)) {
				tictics = 11;
			} else if (type.equalsIgnoreCase(TACTICS_BUS_NOTSUBWAY)) {
				tictics = 11;
			} else if (type.equalsIgnoreCase(TACTICS_BUS_LESSCHANGE)) {
				tictics = 11;
			} else if (type.equalsIgnoreCase(TACTICS_BUS_LESSWALK)) {
				tictics = 12;
			}
		}

		int radius = -1;
		if (answerObj.has("radius")) {
			radius = Integer.valueOf(answerObj.getString("radius"));
		}

		String poi = null;
		if (answerObj.has("poi")) {
			poi = answerObj.getString("poi");
		}

		String base = null;
		if (answerObj.has("base")) {
			base = answerObj.getString("base");
		}

		String line = null;
		if (answerObj.has("line")) {
			line = answerObj.getString("line");
		}

		String station = null;
		if (answerObj.has("station")) {
			station = answerObj.getString("station");
		}

		/* dispatch query */
		if (topic.equalsIgnoreCase(TOPIC_CAR_ROUTE_QUERY)) {
			array = carRouteQuery(start, end, currentCity, tictics);
		} else if (topic.equalsIgnoreCase(TOPIC_CAR_ROUTE_NEARBY_QUERY)) {
			array = carRouteNearbyQuery((float) lat, (float) lon, end,
					currentCity);
		} else if (topic.equalsIgnoreCase(TOPIC_CAR_ROUTE_TEXI_QUERY)) {
			array = texiQuery(start, end, currentCity);
		} else if (topic.equalsIgnoreCase(TOPIC_CAR_ROUTE_QUERY_WITHMID_POINT)) {
			array = carRouteWithMidQuery(start, mid, end, currentCity, tictics);
		} else if (topic.equalsIgnoreCase(TOPIC_CAR_ROUTE_WITH_MID_ROAD)) {
			array = carRouteWithMidQuery(start, mid, end, currentCity, tictics);
		} else if (topic.equalsIgnoreCase(TOPIC_DISTANCE_QUERY)) {
			array = distanceQuery(start, end, currentCity);
		} else if (topic.equalsIgnoreCase(TOPIC_CURRENT_LOCATION_QUERY)) {
			array = currentLocationQuery((float) lat, (float) lon);
		} else if (topic.equalsIgnoreCase(TOPIC_POI_QUERY)) {
			array = poiQuery(poi, base, (float) lat, (float) lon, radius,
					currentCity);
		} else if (topic.equalsIgnoreCase(TOPIC_POI_POSTCODE_QUERY)) {
			array = poiQuery(poi, CURRENT_LOCATION, (float) lat, (float) lon,
					-1, currentCity);
		} else if (topic.equalsIgnoreCase(TOPIC_POI_PHONE_QUERY)) {
			array = poiQuery(poi, CURRENT_LOCATION, 0, 0, -1, currentCity);
		} else if (topic.equalsIgnoreCase(TOPIC_BUS_ROUTE_QUERY)) {
			array = busRouteQuery(start, end, currentCity, tictics);
		} else if (topic.equalsIgnoreCase(TOPIC_BUS_LINE_QUERY)) {
			if (currentCity != null) {
				currentCity = currentCity.replace("市", "").replace("县", "");
			}
			if (type == null) {
				return null;
			}
			if (type.equalsIgnoreCase(BUS_LINE_FIRST_TIME)) {
				array = busLineTimeQuery(line, currentCity);
			} else if (type.equalsIgnoreCase(BUS_LINE_LAST_TIME)) {
				array = busLineTimeQuery(line, currentCity);
			} else if (type.equalsIgnoreCase(BUS_LINE_FIRST_LAST_TIME)) {
				array = busLineTimeQuery(line, currentCity);
			} else if (type.equalsIgnoreCase(BUS_LINE_CHECK_LINE_STATION)) {
				array = busLineListQuery(line, currentCity);
			} else if (type.equalsIgnoreCase(BUS_LINE_LIST_LINE_STATION)) {
				array = busLineListQuery(line, currentCity);
			}
		} else if (topic.equalsIgnoreCase(TOPIC_BUS_STATION_QUERY)) {
			if (currentCity != null) {
				currentCity = currentCity.replace("市", "").replace("县", "");
			}
			array = busStationQuery(station, currentCity);
		} else {
			array = defaultQuery();
		}

		return array;
	}

	private JSONArray defaultQuery() throws JSONException {
		JSONArray array = new JSONArray();
		JSONObject article = new JSONObject();
		article.put("title", mQuestion);
		article.put("picurl", DEFAULT_MAP_PIC_URL);
		article.put("url", mMapPageUrl);
		article.put("position", "first");
		array.put(article);
		return array;
	}

	private DirectionBean executeDirection(String start, String end,
			String mode, int tictics, String originCity, String destCity,
			String region) {
		RouteSearch search = new RouteSearch();
		search.setOrigin(start);
		search.setDestination(end);
		search.setMode(mode);
		search.setOrigin_region(originCity);
		search.setDestination_region(destCity);
		search.setRegion(region);
		search.setTactics(tictics);
		DirectionBean direction = search.execute();
		return direction;
	}

	public ArrayList<POIBean> executePOISearch(String poi, String region,
			boolean searchNearby, int radius, float lat, float lon) {
		POISearch search = new POISearch();
		search.setQuery(poi);
		search.setRegion(region);
		search.setPageNum(0);
		search.setSearchNearby(searchNearby);
		search.setLat(lat);
		search.setLng(lon);
		search.setRadius(radius);
		search.setFilter(false);
		ArrayList<POIBean> list = search.execute();
		return list;
	}

	private ArrayList<LineBean> executeBusLineSearch(String line,
			String currentCity) {
		LineSearch lineSearch = new LineSearch();
		lineSearch.setCity(currentCity);
		lineSearch.setQ(line);
		lineSearch.setWith_xys(0);
		return lineSearch.execute();
	}

	/**
	 * 查询行车路线
	 * 
	 * @param start
	 * @param end
	 * @param currentCity
	 * @param tactics
	 * @return
	 * @throws JSONException
	 */
	private JSONArray carRouteQuery(String start, String end,
			String currentCity, int tictics) throws JSONException {
		JSONArray array = new JSONArray();
		DirectionBean direction = executeDirection(start, end,
				DIRECTION_MODE_DRIVING, tictics, currentCity, currentCity,
				currentCity);

		if (direction.getType() == 1) {
			String originCity = currentCity;
			String destinationCity = currentCity;
			String origin = start;
			String destination = end;

			if (direction.getOriginCandidate() != null
					&& direction.getOriginCandidate().getContent() != null
					&& direction.getOriginCandidate().getContent().size() > 0) {
				if (direction.getOriginCandidate().getListType() == 0) {
					origin = direction.getOriginCandidate().getContent().get(0)
							.getLocation().getLat()
							+ ","
							+ direction.getOriginCandidate().getContent()
									.get(0).getLocation().getLng();
					if (direction.getOriginCandidate().getCityName() != null) {
						originCity = direction.getOriginCandidate()
								.getCityName();
					}
				} else {
					originCity = direction.getOriginCandidate().getContent()
							.get(0).getName();
				}
			} else {
				return null;
			}

			if (direction.getDestinationCandidate() != null
					&& direction.getDestinationCandidate().getContent() != null
					&& direction.getDestinationCandidate().getContent().size() > 0) {
				if (direction.getDestinationCandidate().getListType() == 0) {
					destination = direction.getDestinationCandidate()
							.getContent().get(0).getLocation().getLat()
							+ ","
							+ direction.getDestinationCandidate().getContent()
									.get(0).getLocation().getLng();
					if (direction.getDestinationCandidate().getCityName() != null) {
						destinationCity = direction.getDestinationCandidate()
								.getCityName();
					}
				} else {
					destinationCity = direction.getDestinationCandidate()
							.getContent().get(0).getName();
				}
			} else {
				return null;
			}
			direction = executeDirection(origin, destination,
					DIRECTION_MODE_DRIVING, tictics, originCity,
					destinationCity, currentCity);
		}

		if (direction.getType() == 2) {
			if (direction.getRoutes() != null
					&& direction.getRoutes().size() > 0) {
				Route route = direction.getRoutes().get(0);
				List<Step> steps = route.getSteps();
				StringBuffer stepSb = new StringBuffer();
				for (int i = 0; i < steps.size(); i++) {
					stepSb.append(i + 1 + ".");
					stepSb.append(steps.get(i).getInstructions());
					stepSb.append("\n");
				}

				JSONObject article = new JSONObject();
				article.put("title", "问题：" + mQuestion + " - 点击进入地图");
				article.put("picurl", DEFAULT_MAP_PIC_URL);
				article.put("url", mMapPageUrl);
				article.put("position", "first");
				array.put(article);
				JSONObject desc = new JSONObject();
				desc.put("title", "全程约" + route.getDistance() + "米," + "预计需要"
						+ (route.getDuration() / 60 + 1) + "分钟");
				array.put(desc);
				JSONObject detail = new JSONObject();
				detail.put("title", stepSb.toString());
				array.put(detail);
			} else {
				return null;
			}
		}
		return array;
	}

	/**
	 * 查询去周边兴趣点行车路线
	 * 
	 * @param start
	 * @param end
	 * @param currentCity
	 * @param tactics
	 * @return
	 * @throws JSONException
	 *             JSONArray poiQuery(String poi, String base, float lat, float
	 *             lon, int radius, String currentCity)
	 */
	private JSONArray carRouteNearbyQuery(float lat, float lon, String poi,
			String currentCity) throws JSONException {
		return poiQuery(poi, CURRENT_LOCATION, lat, lon, DEFAULT_RADIUS,
				currentCity);
	}

	/**
	 * 查询打的费用
	 * 
	 * @param start
	 * @param end
	 * @param city
	 * @return
	 * @throws JSONException
	 */
	private JSONArray texiQuery(String start, String end, String currentCity)
			throws JSONException {
		JSONArray array = new JSONArray();
		DirectionBean direction = executeDirection(start, end,
				DIRECTION_MODE_DRIVING, 11, currentCity, currentCity,
				currentCity);

		if (direction.getType() == 1) {
			String originCity = currentCity;
			String destinationCity = currentCity;
			String origin = start;
			String destination = end;

			if (direction.getOriginCandidate() != null
					&& direction.getOriginCandidate().getContent() != null
					&& direction.getOriginCandidate().getContent().size() > 0) {
				if (direction.getOriginCandidate().getListType() == 0) {
					origin = direction.getOriginCandidate().getContent().get(0)
							.getLocation().getLat()
							+ ","
							+ direction.getOriginCandidate().getContent()
									.get(0).getLocation().getLng();
					originCity = direction.getOriginCandidate().getCityName();
				} else {
					originCity = direction.getOriginCandidate().getContent()
							.get(0).getName();
				}
			} else {
				return null;
			}

			if (direction.getDestinationCandidate() != null
					&& direction.getDestinationCandidate().getContent() != null
					&& direction.getDestinationCandidate().getContent().size() > 0) {
				if (direction.getDestinationCandidate().getListType() == 0) {
					destination = direction.getDestinationCandidate()
							.getContent().get(0).getLocation().getLat()
							+ ","
							+ direction.getDestinationCandidate().getContent()
									.get(0).getLocation().getLng();
					destinationCity = direction.getDestinationCandidate()
							.getCityName();
				} else {
					destinationCity = direction.getDestinationCandidate()
							.getContent().get(0).getName();
				}
			} else {
				return null;
			}
			direction = executeDirection(origin, destination,
					DIRECTION_MODE_DRIVING, 11, originCity, destinationCity,
					currentCity);
		}

		if (direction.getType() == 2) {
			if (direction.getTaxi() != null) {
				Taxi taxi = direction.getTaxi();
				int distance = taxi.getDistance();
				int duration = taxi.getDuration();
				String remark = taxi.getRemark();
				List<String> details = taxi.getDetail();

				JSONObject article = new JSONObject();
				article.put("title", "问题：" + mQuestion + " - 点击进入地图");
				article.put("picurl", DEFAULT_MAP_PIC_URL);
				article.put("url", mMapPageUrl);
				article.put("position", "first");
				array.put(article);

				if (remark != null && !remark.equalsIgnoreCase("")) {
					JSONObject desc = new JSONObject();
					desc.put("title", remark);
					array.put(desc);
				}

				if (details != null) {
					for (String detail : details) {
						JSONObject detailObj = new JSONObject();
						detailObj.put("title", detail);
						array.put(detailObj);
					}
				}
			} else {
				return null;
			}
		}
		return array;
	}

	/**
	 * 有中间点的行车路线查询
	 * 
	 * @param start
	 * @param mid
	 * @param end
	 * @param currentCity
	 * @param tactics
	 * @return
	 * @throws JSONException
	 */
	private JSONArray carRouteWithMidQuery(String start, String mid,
			String end, String currentCity, int tictics) throws JSONException {
		return carRouteQuery(start, end, currentCity, tictics);
	}

	/**
	 * 两地距离查询
	 * 
	 * @param start
	 * @param end
	 * @param currentCity
	 * @return
	 * @throws JSONException
	 */
	private JSONArray distanceQuery(String start, String end, String currentCity)
			throws JSONException {
		JSONArray array = new JSONArray();
		DirectionBean direction = executeDirection(start, end,
				DIRECTION_MODE_DRIVING, 11, currentCity, currentCity,
				currentCity);

		if (direction.getType() == 1) {
			String originCity = currentCity;
			String destinationCity = currentCity;
			String origin = start;
			String destination = end;

			if (direction.getOriginCandidate() != null
					&& direction.getOriginCandidate().getContent() != null
					&& direction.getOriginCandidate().getContent().size() > 0) {
				if (direction.getOriginCandidate().getListType() == 0) {
					origin = direction.getOriginCandidate().getContent().get(0)
							.getLocation().getLat()
							+ ","
							+ direction.getOriginCandidate().getContent()
									.get(0).getLocation().getLng();
					originCity = direction.getOriginCandidate().getCityName();
				} else {
					originCity = direction.getOriginCandidate().getContent()
							.get(0).getName();
				}
			} else {
				return null;
			}

			if (direction.getDestinationCandidate() != null
					&& direction.getDestinationCandidate().getContent() != null
					&& direction.getDestinationCandidate().getContent().size() > 0) {
				if (direction.getDestinationCandidate().getListType() == 0) {
					destination = direction.getDestinationCandidate()
							.getContent().get(0).getLocation().getLat()
							+ ","
							+ direction.getDestinationCandidate().getContent()
									.get(0).getLocation().getLng();
					destinationCity = direction.getDestinationCandidate()
							.getCityName();
				} else {
					destinationCity = direction.getDestinationCandidate()
							.getContent().get(0).getName();
				}
			} else {
				return null;
			}
			direction = executeDirection(origin, destination,
					DIRECTION_MODE_DRIVING, 11, originCity, destinationCity,
					currentCity);
		}

		if (direction.getType() == 2) {
			if (direction.getRoutes() != null
					&& direction.getRoutes().size() > 0) {
				Route route = direction.getRoutes().get(0);
				int distance = route.getDistance();
				int duration = route.getDuration();
				JSONObject article = new JSONObject();
				article.put("title", "问题：" + mQuestion + " - 点击进入地图");
				article.put("picurl", DEFAULT_MAP_PIC_URL);
				article.put("url", mMapPageUrl);
				article.put("description", "全程约" + distance + "米," + "预计需要"
						+ (duration / 60 + 1) + "分钟");
				article.put("position", "first");
				array.put(article);
			} else {
				return null;
			}
		}
		return array;
	}

	/**
	 * 当前位置查询
	 * 
	 * @param lat
	 * @param lon
	 * @return
	 * @throws JSONException
	 */
	private JSONArray currentLocationQuery(float lat, float lon)
			throws JSONException {
		JSONArray array = new JSONArray();
		ReGeoCoding search = new ReGeoCoding();
		search.setLat(lat);
		search.setLng(lon);
		search.setPois(0);
		GeoBean geo = search.execute();
		if (geo != null) {
			String address = geo.getFormatted_address();
			String business = geo.getBusiness();
			String description = geo.getSematic_description();
			if (address == null || address.equalsIgnoreCase("")) {
				return null;
			}
			StringBuffer sb = new StringBuffer();
			sb.append("当前位于");
			sb.append(address);
			if (description != null && !description.equalsIgnoreCase("")) {
				sb.append("," + description);
			}
			if (business != null && !business.equalsIgnoreCase("")) {
				sb.append(",附近有" + business + ".");
			}

			JSONObject article = new JSONObject();
			article.put("title", "问题：" + mQuestion + " - 点击进入地图");
			article.put("picurl", DEFAULT_MAP_PIC_URL);
			article.put("url", mMapPageUrl);
			article.put("description", sb.toString());
			article.put("position", "first");
			array.put(article);
			return array;
		} else {
			return null;
		}
	}

	/**
	 * 兴趣点查询
	 * 
	 * @param poi
	 * @param base
	 * @param lat
	 * @param lon
	 * @param radius
	 * @param currentCity
	 * @return
	 * @throws JSONException
	 * @throws Exception
	 */
	private JSONArray poiQuery(String poi, String base, float lat, float lon,
			int radius, String currentCity) throws JSONException {
		JSONArray array = new JSONArray();
		ArrayList<POIBean> poiList = null;
		if (base != null && !base.equalsIgnoreCase(CURRENT_LOCATION)) {
			ArrayList<POIBean> baseList = executePOISearch(base, currentCity,
					false, DEFAULT_RADIUS, lat, lon);
			if (baseList != null && baseList.size() > 0) {
				POIBean basePOI = baseList.get(0);
				poiList = executePOISearch(poi, currentCity, true,
						DEFAULT_RADIUS, basePOI.getLocation().getLat(), basePOI
								.getLocation().getLng());
			} else {
				return null;
			}
		} else {
			poiList = executePOISearch(poi, currentCity, true, DEFAULT_RADIUS,
					lat, lon);
		}

		if (poiList != null && poiList.size() > 0) {
			JSONObject article = new JSONObject();
			article.put("title", "问题：" + mQuestion + " - 点击进入地图");
			article.put("picurl", DEFAULT_MAP_PIC_URL);
			article.put("url", mMapPageUrl);
			article.put("position", "first");
			array.put(article);

			for (POIBean p : poiList) {
				String name = p.getName();
				String address = p.getAddress();
				String telephone = p.getTelephone();
				String detailUrl = null;
				String price = null;
				String rating = null;
				int distance = 0;
				DetailInfo info = p.getDetail_info();
				if (info != null) {
					detailUrl = info.getDetail_url();
					price = info.getPrice();
					rating = info.getOverall_rating();
					distance = info.getDistance();
				}
				if (name != null && address != null) {
					StringBuffer sb = new StringBuffer();
					sb.append(name);
					sb.append("\n");
					if (rating != null) {
						sb.append("评分:" + rating);
						if (price == null) {
							sb.append("\n");
						}
					}
					if (price != null) {
						if (rating != null) {
							sb.append(" ");
						}
						sb.append("人均:" + price + "元");
						sb.append("\n");
					}
					if (base.equalsIgnoreCase(CURRENT_LOCATION)) {
						sb.append("离我" + distance + "米");
						sb.append("\n");
					}
					sb.append(address);
					sb.append("\n");
					if (telephone != null) {
						sb.append("电话:" + telephone);
					}
					JSONObject poiItemObj = new JSONObject();
					poiItemObj.put("title", sb.toString());
					if (detailUrl != null) {
						poiItemObj.put("url", detailUrl);
					}
					array.put(poiItemObj);
				}
			}
			return array;
		} else {
			return null;
		}
	}

	/**
	 * 公交路线规划
	 * 
	 * @param start
	 * @param end
	 * @param currentCity
	 * @param tactics
	 * @return
	 * @throws JSONException
	 */
	private JSONArray busRouteQuery(String start, String end,
			String currentCity, int tictics) throws JSONException {
		JSONArray array = new JSONArray();
		DirectionBean direction = executeDirection(start, end,
				DIRECTION_MODE_TRANSIT, tictics, currentCity, currentCity,
				currentCity);

		if (direction.getType() == 1) {
			String originCity = currentCity;
			String destinationCity = currentCity;
			String origin = start;
			String destination = end;
			boolean startExist = true;
			boolean endExist = true;

			if (direction.getOriginCandidate() != null
					&& direction.getOriginCandidate().getContent() != null
					&& direction.getOriginCandidate().getContent().size() > 0) {
				if (direction.getOriginCandidate().getListType() == 0) {
					origin = direction.getOriginCandidate().getContent().get(0)
							.getLocation().getLat()
							+ ","
							+ direction.getOriginCandidate().getContent()
									.get(0).getLocation().getLng();
					if (direction.getOriginCandidate().getCityName() != null) {
						originCity = direction.getOriginCandidate()
								.getCityName();
					}
				} else {
					originCity = direction.getOriginCandidate().getContent()
							.get(0).getName();
				}
			} else {
				startExist = false;
			}

			if (direction.getDestinationCandidate() != null
					&& direction.getDestinationCandidate().getContent() != null
					&& direction.getDestinationCandidate().getContent().size() > 0) {
				if (direction.getDestinationCandidate().getListType() == 0) {
					destination = direction.getDestinationCandidate()
							.getContent().get(0).getLocation().getLat()
							+ ","
							+ direction.getDestinationCandidate().getContent()
									.get(0).getLocation().getLng();
					if (direction.getDestinationCandidate().getCityName() != null) {
						destinationCity = direction.getDestinationCandidate()
								.getCityName();
					}
				} else {
					destinationCity = direction.getDestinationCandidate()
							.getContent().get(0).getName();
				}
			} else {
				endExist = false;
			}

			if (!startExist && !endExist) {
				return null;
			}
			direction = executeDirection(origin, destination,
					DIRECTION_MODE_TRANSIT, tictics, originCity,
					destinationCity, currentCity);
		}

		if (direction.getType() == 2) {
			if (direction.getScheme() != null
					&& direction.getScheme().size() > 0) {
				ArrayList<Scheme> schemeList = direction.getScheme().get(0);
				if (schemeList != null && schemeList.size() > 0) {
					Scheme scheme = schemeList.get(0);
					String arrivTime = scheme.getArrive_time();
					int distance = scheme.getDistance();
					int duration = scheme.getDuration();
					List<TransitStep> busSteps = new ArrayList<TransitStep>();
					List<ArrayList<TransitStep>> steps = scheme.getSteps();
					if (steps != null && steps.size() > 0) {
						for (ArrayList<TransitStep> tList : steps) {
							if (tList != null) {
								busSteps.addAll(tList);
							}
						}

						JSONObject article = new JSONObject();
						article.put("title", "问题：" + mQuestion + " - 点击进入地图");
						article.put("picurl", DEFAULT_MAP_PIC_URL);
						article.put("url", mMapPageUrl);
						article.put("position", "first");
						array.put(article);

						StringBuffer sb = new StringBuffer();
						if (distance > 0) {
							sb.append("路线总长:");
							sb.append(distance);
							sb.append("米\n");
						}
						if (duration > 0) {
							sb.append("预计耗时:");
							sb.append(duration / 60 + 1);
							sb.append("分钟\n");
						}
						if (arrivTime != null
								&& !arrivTime.equalsIgnoreCase("")
								&& arrivTime.contains("T")) {
							arrivTime = arrivTime.split("T")[1];
							sb.append("预计抵达时间:");
							sb.append(arrivTime);
							sb.append("\n");
						}
						JSONObject desc = new JSONObject();
						desc.put("title", sb.toString());
						array.put(desc);

						sb = new StringBuffer();
						sb.append("起点出发->");
						for (int i = 0; i < busSteps.size(); i++) {
							TransitStep t = busSteps.get(i);
							String instruction = t.getStepInstruction();
							if (instruction != null
									&& !instruction.equalsIgnoreCase("")) {
								sb.append(t.getStepInstruction());
								sb.append("->");
							}
						}
						sb.append("抵达终点");
						JSONObject detail = new JSONObject();
						detail.put("title", sb.toString());
						array.put(detail);
					} else {
						return null;
					}
				} else {
					return null;
				}
			} else {
				JSONObject article = new JSONObject();
				article.put("title", "问题：" + mQuestion + " - 点击进入地图");
				article.put("picurl", DEFAULT_MAP_PIC_URL);
				article.put("url", mMapPageUrl);
				article.put("position", "first");
				array.put(article);
				JSONObject desc = new JSONObject();
				desc.put("title", "抱歉，没有找到公交路线，您可以尝试打的去");
				array.put(desc);

				Taxi taxi = direction.getTaxi();
				if (taxi != null) {
					int distance = taxi.getDistance();
					int duration = taxi.getDuration();
					String remark = taxi.getRemark();
					List<String> details = taxi.getDetail();

					if (remark != null && !remark.equalsIgnoreCase("")) {
						JSONObject texi = new JSONObject();
						texi.put("title", remark);
						array.put(texi);
					}

					if (details != null) {
						for (String detail : details) {
							JSONObject detailObj = new JSONObject();
							detailObj.put("title", detail);
							array.put(detailObj);
						}
					}
				}
			}
		}
		return array;
	}

	/**
	 * 公交首末班时间查询
	 * 
	 * @param line
	 * @param currentCity
	 * @return
	 * @throws JSONException
	 */
	private JSONArray busLineTimeQuery(String line, String currentCity)
			throws JSONException {
		ArrayList<LineBean> lineList = executeBusLineSearch(line, currentCity);
		JSONArray array = new JSONArray();
		JSONObject article = new JSONObject();
		article.put("title", "问题：" + mQuestion + " - 点击进入地图");
		article.put("picurl", DEFAULT_MAP_PIC_URL);
		article.put("url", mMapPageUrl);
		article.put("position", "first");
		array.put(article);

		if (lineList != null && lineList.size() > 0) {
			for (LineBean l : lineList) {
				String name = l.getName();
				String info = l.getInfo();
				if (name != null && info != null) {
					StringBuffer sb = new StringBuffer();
					sb.append(name);
					sb.append("\n");
					sb.append(info);
					JSONObject lineObj = new JSONObject();
					lineObj.put("title", sb.toString());
					array.put(lineObj);
				}
			}
			return array;
		} else {
			return null;
		}
	}

	/**
	 * 查询公交停靠站点
	 * 
	 * @param line
	 * @param currentCity
	 * @return
	 * @throws JSONException
	 */
	private JSONArray busLineListQuery(String line, String currentCity)
			throws JSONException {
		ArrayList<LineBean> lineList = executeBusLineSearch(line, currentCity);
		JSONArray array = new JSONArray();
		JSONObject article = new JSONObject();
		article.put("title", "问题：" + mQuestion + " - 点击进入地图");
		article.put("picurl", DEFAULT_MAP_PIC_URL);
		article.put("url", mMapPageUrl);
		article.put("position", "first");
		array.put(article);

		if (lineList != null && lineList.size() > 0) {
			for (LineBean l : lineList) {
				String name = l.getName();
				String info = l.getInfo();
				String stats = l.getStats();
				if (name != null && info != null && stats != null) {
					StringBuffer sb = new StringBuffer();
					sb.append(name);
					sb.append("\n");
					sb.append(info);
					sb.append("\n");
					sb.append("经过站点:");
					String[] stations = stats.split(";");
					for (int i = 0; i < stations.length; i++) {
						sb.append(stations[i]);
						if (i != stations.length - 1) {
							sb.append(",");
						}
					}
					JSONObject lineObj = new JSONObject();
					lineObj.put("title", sb.toString());
					array.put(lineObj);
				}
			}
			return array;
		} else {
			return null;
		}
	}

	/**
	 * 查询经过站点的公交
	 * 
	 * @param station
	 * @param currentCity
	 * @return
	 * @throws JSONException
	 */
	private JSONArray busStationQuery(String station, String currentCity)
			throws JSONException {
		StatsSearch statsSearch = new StatsSearch();
		statsSearch.setCity(currentCity);
		statsSearch.setQ(station);
		ArrayList<StatBean> stats = statsSearch.execute();
		if (stats != null && stats.size() > 0) {
			JSONArray array = new JSONArray();
			JSONObject article = new JSONObject();
			article.put("title", "问题：" + mQuestion + " - 点击进入地图");
			article.put("picurl", DEFAULT_MAP_PIC_URL);
			article.put("url", mMapPageUrl);
			article.put("position", "first");
			array.put(article);

			for (StatBean stat : stats) {
				String name = stat.getName();
				String lineNames = stat.getLine_names();
				if (name != null && lineNames != null) {
					StringBuffer sb = new StringBuffer();
					sb.append("站点:" + name + "\n");
					sb.append(lineNames);

					JSONObject lineObj = new JSONObject();
					lineObj.put("title", sb.toString());
					array.put(lineObj);
				}
			}
			return array;
		} else {
			return null;
		}
	}

	public static void main(String[] args) throws JSONException {
		String question = "从联升佳苑去天一广场怎么坐公交";
		String json = HttpUtils
				.doGet("http://rsvpservice.rsvptech.cn/rsvpnavinfo/cn-vertical/qa/"
						+ question);
		System.out.println(json);
		MapServiceHandler mapInstance = MapServiceHandler.getInstence();
		JSONArray array = mapInstance.execute(json, 29.875964, 121.560824,
				question);
		System.out.println(array);
	}
}
